// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 商品数据
    let products = [
        {
            id: 1,
            name: '我的第一本物理启蒙书',
            author: '冰河 著',
            code: '1211001',
            category: '知识启蒙',
            price: 18.00,
            stock: 2,
            sales: 4,
            status: '上架中',
            image: './img/zhi2.jpg',
            description: '一本生动有趣的物理启蒙书，让孩子爱上科学。'
        },
        {
            id: 2,
            name: '忙忙碌碌镇',
            author: '理查德·斯凯瑞 著',
            code: '1211002',
            category: '知识启蒙',
            price: 18.00,
            stock: 5,
            sales: 12,
            status: '上架中',
            image: './img/zhi1.jpg',
            description: '经典的儿童认知绘本，充满趣味的场景。'
        },
        {
            id: 3,
            name: '快乐的小熊',
            author: '麦克·格雷涅茨 著',
            code: '1211003',
            category: '品德教育',
            price: 22.00,
            stock: 8,
            sales: 6,
            status: '上架中',
            image: './img/pin1.jpg',
            description: '一个关于友情和分享的温暖故事。'
        }
    ];

    // 获取DOM元素
    const modal = document.getElementById('addProductModal');
    const addProductBtn = document.querySelector('.btn.btn-primary');
    const searchInput = document.querySelector('.admin-search input');
    const productTable = document.querySelector('.product-table tbody');
    const categorySelect = document.querySelector('.filter-item select');
    const statusSelect = document.querySelector('.filter-item:nth-child(2) select');
    const minPriceInput = document.querySelector('.price-input:first-of-type');
    const maxPriceInput = document.querySelector('.price-input:last-of-type');

    // 分页配置
    const paginationConfig = {
        itemsPerPage: 10,
        currentPage: 1,
        totalPages: 1
    };

    // 初始化页面
    function initializePage() {
        initializeCategoryFilter();
        updateProductTable(products);
        updateStatistics();
    }

    // 更新统计数据
    function updateStatistics() {
        const totalProducts = products.length;
        const activeProducts = products.filter(p => p.status === '上架中').length;
        const lowStock = products.filter(p => p.stock < 5).length;
        const newThisMonth = products.filter(p => p.id > products.length - 3).length;

        document.querySelector('.data-card:nth-child(1) p').textContent = totalProducts;
        document.querySelector('.data-card:nth-child(2) p').textContent = activeProducts;
        document.querySelector('.data-card:nth-child(3) p').textContent = lowStock;
        document.querySelector('.data-card:nth-child(4) p').textContent = newThisMonth;
    }

    // 更新商品表格（添加分页）
    function updateProductTable(filteredProducts) {
        productTable.innerHTML = '';
        
        if (filteredProducts.length === 0) {
            productTable.innerHTML = `
                <tr>
                    <td colspan="9" style="text-align: center; padding: 20px;">
                        暂无相关商品数据
                    </td>
                </tr>
            `;
            updatePagination(0);
            return;
        }

        // 计算分页数据
        const startIndex = (paginationConfig.currentPage - 1) * paginationConfig.itemsPerPage;
        const endIndex = startIndex + paginationConfig.itemsPerPage;
        const paginatedProducts = filteredProducts.slice(startIndex, endIndex);

        // 更新表格内容
        paginatedProducts.forEach(product => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td><input type="checkbox" class="row-checkbox"></td>
                <td>
                    <div class="product-info">
                        <img src="${product.image}" alt="${product.name}">
                        <div class="product-detail">
                            <h4>${product.name}</h4>
                            <p>${product.author}</p>
                        </div>
                    </div>
                </td>
                <td>${product.code}</td>
                <td>${product.category}</td>
                <td>¥${product.price.toFixed(2)}</td>
                <td>${product.stock}</td>
                <td>${product.sales}</td>
                <td>
                    <span class="status-tag ${product.status === '上架中' ? 'status-active' : 'status-inactive'}">
                        ${product.status}
                    </span>
                </td>
                <td>
                    <button class="btn-action edit" title="编辑" data-id="${product.id}">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn-action view" title="查看" data-id="${product.id}">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="btn-action delete" title="删除" data-id="${product.id}">
                        <i class="fas fa-trash-alt"></i>
                    </button>
                </td>
            `;
            productTable.appendChild(row);

            // 添加操作按钮的事件监听
            addActionButtonListeners(row, product);

            // 添加删除按钮事件监听
            const deleteBtn = row.querySelector('.delete');
            deleteBtn.addEventListener('click', () => deleteProduct(product.id));
        });

        // 更新分页控件
        updatePagination(filteredProducts.length);
    }

    // 更新分页控件
    function updatePagination(totalItems) {
        const pagination = document.querySelector('.pagination');
        const totalPages = Math.ceil(totalItems / paginationConfig.itemsPerPage);
        paginationConfig.totalPages = totalPages;

        // 更新总记录数
        const pageInfo = pagination.querySelector('.page-info');
        pageInfo.textContent = `共 ${totalItems} 条记录`;

        // 更新分页按钮
        const pageControls = pagination.querySelector('.page-controls');
        pageControls.innerHTML = '';

        // 添加首页和上一页按钮
        pageControls.innerHTML += `
            <button class="page-btn" ${paginationConfig.currentPage === 1 ? 'disabled' : ''} data-page="1">
                <i class="fas fa-angle-double-left"></i>
            </button>
            <button class="page-btn" ${paginationConfig.currentPage === 1 ? 'disabled' : ''} data-page="${paginationConfig.currentPage - 1}">
                <i class="fas fa-angle-left"></i>
            </button>
        `;

        // 添加页码按钮
        let startPage = Math.max(1, paginationConfig.currentPage - 2);
        let endPage = Math.min(totalPages, startPage + 4);
        
        if (endPage - startPage < 4) {
            startPage = Math.max(1, endPage - 4);
        }

        for (let i = startPage; i <= endPage; i++) {
            pageControls.innerHTML += `
                <button class="page-btn ${i === paginationConfig.currentPage ? 'active' : ''}" data-page="${i}">
                    ${i}
                </button>
            `;
        }

        // 添加末页和下一页按钮
        pageControls.innerHTML += `
            <button class="page-btn" ${paginationConfig.currentPage === totalPages ? 'disabled' : ''} data-page="${paginationConfig.currentPage + 1}">
                <i class="fas fa-angle-right"></i>
            </button>
            <button class="page-btn" ${paginationConfig.currentPage === totalPages ? 'disabled' : ''} data-page="${totalPages}">
                <i class="fas fa-angle-double-right"></i>
            </button>
        `;

        // 添加分页按钮点击事件
        const pageButtons = pageControls.querySelectorAll('.page-btn');
        pageButtons.forEach(button => {
            button.addEventListener('click', function() {
                if (this.hasAttribute('disabled')) return;
                
                const page = parseInt(this.dataset.page);
                if (page !== paginationConfig.currentPage) {
                    paginationConfig.currentPage = page;
                    filterProducts();
                }
            });
        });
    }

    // 添加每页显示数量选择功能
    const pageSizeSelect = document.querySelector('.page-size');
    if (pageSizeSelect) {
        pageSizeSelect.addEventListener('change', function() {
            paginationConfig.itemsPerPage = parseInt(this.value);
            paginationConfig.currentPage = 1;
            filterProducts();
        });
    }

    // 搜索和筛选商品
    function filterProducts() {
        const searchTerm = searchInput.value.toLowerCase().trim();
        const selectedCategory = categorySelect.value;
        const selectedStatus = statusSelect.value;
        const minPrice = parseFloat(minPriceInput.value) || 0;
        const maxPrice = parseFloat(maxPriceInput.value) || Infinity;

        const filteredProducts = products.filter(product => {
            const matchesSearch = 
                product.name.toLowerCase().includes(searchTerm) ||
                product.code.toLowerCase().includes(searchTerm) ||
                product.author.toLowerCase().includes(searchTerm);

            const matchesCategory = !selectedCategory || 
                product.category === selectedCategory;

            const matchesStatus = !selectedStatus || 
                (selectedStatus === '1' && product.status === '上架中') ||
                (selectedStatus === '2' && product.status === '已下架') ||
                (selectedStatus === '3' && product.status === '售罄');

            const matchesPrice = 
                product.price >= minPrice && 
                product.price <= maxPrice;

            return matchesSearch && matchesCategory && matchesStatus && matchesPrice;
        });

        updateProductTable(filteredProducts);
        updateStatistics();
    }

    // 添加分类点击事件
    function initializeCategoryFilter() {
        // 清空现有选项
        categorySelect.innerHTML = `
            <option value="">全部</option>
            <option value="知识启蒙类">知识启蒙类</option>
            <option value="品德教育类">品德教育类</option>
            <option value="语言表达类">语言表达类</option>
        `;

        // 添加分类点击事件
        categorySelect.addEventListener('change', function(e) {
            const selectedCategory = e.target.value;
            
            // 筛选对应分类的商品
            const filteredProducts = selectedCategory ? 
                products.filter(product => product.category === selectedCategory) : 
                products;

            // 更新商品列表和统计数据
            updateProductTable(filteredProducts);

            // 更新其他筛选条件的状态
            updateFilterStatus(selectedCategory);
        });
    }

    // 更新筛选状态
    function updateFilterStatus(selectedCategory) {
        if (selectedCategory) {
            console.log(`当前选择的分类: ${selectedCategory}`);
            
            // 更新分类相关的统计数据
            const categoryProducts = products.filter(p => p.category === selectedCategory);
            const categoryStats = {
                total: categoryProducts.length,
                active: categoryProducts.filter(p => p.status === '上架中').length,
                lowStock: categoryProducts.filter(p => p.stock < 5).length,
                newThisMonth: categoryProducts.filter(p => p.id > products.length - 3).length
            };
            
            // 更新统计卡片显示
            document.querySelector('.data-card:nth-child(1) p').textContent = categoryStats.total;
            document.querySelector('.data-card:nth-child(2) p').textContent = categoryStats.active;
            document.querySelector('.data-card:nth-child(3) p').textContent = categoryStats.lowStock;
            document.querySelector('.data-card:nth-child(4) p').textContent = categoryStats.newThisMonth;
        } else {
            // 如果选择"全部"，恢复显示所有商品的统计数据
            updateStatistics();
        }
    }

    // 修改商品数据中的分类名称
    products = products.map(product => ({
        ...product,
        category: product.category + '类'  // 添加"类"后缀
    }));

    // 打开添加商品弹窗
    function openModal() {
        // 创建模态框
        const addModal = document.createElement('div');
        addModal.className = 'modal add-product-modal';
        addModal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3>添加新书籍</h3>
                    <button class="close-btn">&times;</button>
                </div>
                <div class="modal-body">
                    <form id="addBookForm" class="add-book-form">
                        <div class="form-group">
                            <label for="productName">书籍名称 <span class="required">*</span></label>
                            <input type="text" id="productName" name="productName" required>
                        </div>
                        <div class="form-group">
                            <label for="author">作者 <span class="required">*</span></label>
                            <input type="text" id="author" name="author" required>
                        </div>
                        <div class="form-group">
                            <label for="productCode">图书编码 <span class="required">*</span></label>
                            <input type="text" id="productCode" name="productCode" required>
                        </div>
                        <div class="form-row">
                            <div class="form-group half">
                                <label for="category">分类 <span class="required">*</span></label>
                                <select id="category" name="category" required>
                                    <option value="">请选择分类</option>
                                    <option value="知识启蒙类">知识启蒙类</option>
                                    <option value="品德教育类">品德教育类</option>
                                    <option value="语言表达类">语言表达类</option>
                                </select>
                            </div>
                            <div class="form-group half">
                                <label for="status">状态 <span class="required">*</span></label>
                                <select id="status" name="status" required>
                                    <option value="1">上架中</option>
                                    <option value="2">已下架</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group half">
                                <label for="price">价格 <span class="required">*</span></label>
                                <input type="number" id="price" name="price" step="0.01" min="0" required>
                            </div>
                            <div class="form-group half">
                                <label for="stock">库存 <span class="required">*</span></label>
                                <input type="number" id="stock" name="stock" min="0" required>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="description">图书描述</label>
                            <textarea id="description" name="description" rows="3"></textarea>
                        </div>
                        <div class="form-group">
                            <label>图书封面 <span class="required">*</span></label>
                            <div class="image-upload-container">
                                <div class="image-upload">
                                    <input type="file" name="image" accept="image/*" required>
                                    <i class="fas fa-cloud-upload-alt"></i>
                                    <p>点击或拖拽上传图片</p>
                                </div>
                            </div>
                        </div>
                        <div class="form-actions">
                            <button type="button" class="btn btn-secondary cancel-btn">取消</button>
                            <button type="submit" class="btn btn-primary save-btn">保存</button>
                        </div>
                    </form>
                </div>
            </div>
        `;

        document.body.appendChild(addModal);
        document.body.style.overflow = 'hidden';

        // 获取表单元素
        const form = addModal.querySelector('#addBookForm');
        const imageUpload = form.querySelector('.image-upload');
        const fileInput = form.querySelector('input[type="file"]');
        const closeBtn = addModal.querySelector('.close-btn');
        const cancelBtn = addModal.querySelector('.cancel-btn');

        // 关闭模态框函数
        const closeAddModal = () => {
            addModal.remove();
            document.body.style.overflow = '';
        };

        // 添加关闭事件监听
        closeBtn.addEventListener('click', closeAddModal);
        cancelBtn.addEventListener('click', closeAddModal);
        addModal.addEventListener('click', e => {
            if (e.target === addModal) closeAddModal();
        });

        // 图片上传处理
        imageUpload.addEventListener('click', () => fileInput.click());
        imageUpload.addEventListener('dragover', e => {
            e.preventDefault();
            imageUpload.classList.add('dragover');
        });
        imageUpload.addEventListener('dragleave', () => {
            imageUpload.classList.remove('dragover');
        });
        imageUpload.addEventListener('drop', e => {
            e.preventDefault();
            imageUpload.classList.remove('dragover');
            const file = e.dataTransfer.files[0];
            if (file && file.type.startsWith('image/')) {
                fileInput.files = e.dataTransfer.files;
                handleImagePreview(file, imageUpload);
            }
        });
        fileInput.addEventListener('change', e => {
            const file = e.target.files[0];
            if (file) handleImagePreview(file, imageUpload);
        });

        // 表单提交处理
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 表单验证
            if (!validateForm(this)) return;

            const formData = new FormData(this);
            
            // 创建新商品对象
            const newProduct = {
                id: products.length + 1,
                name: formData.get('productName'),
                author: formData.get('author'),
                code: formData.get('productCode'),
                category: formData.get('category'),
                price: parseFloat(formData.get('price')),
                stock: parseInt(formData.get('stock')),
                sales: 0,
                status: formData.get('status') === '1' ? '上架中' : '已下架',
                description: formData.get('description') || '',
                image: URL.createObjectURL(formData.get('image'))
            };

            // 检查商品编码是否重复
            if (products.some(p => p.code === newProduct.code)) {
                alert('商品编码已存在，请使用其他编码！');
                return;
            }

            // 添加新商品
            products.push(newProduct);
            updateProductTable(products);
            updateStatistics();
            closeAddModal();
            alert('商品添加成功！');
        });

        // ESC键关闭
        const escHandler = (e) => {
            if (e.key === 'Escape') {
                closeAddModal();
                document.removeEventListener('keydown', escHandler);
            }
        };
        document.addEventListener('keydown', escHandler);
    }

    // 处理图片预览
    function handleImagePreview(file, uploadContainer) {
        const reader = new FileReader();
        reader.onload = function(e) {
            let previewContainer = uploadContainer.parentElement.querySelector('.image-preview');
            if (!previewContainer) {
                previewContainer = document.createElement('div');
                previewContainer.className = 'image-preview';
                const img = document.createElement('img');
                const removeBtn = document.createElement('button');
                removeBtn.className = 'remove-image';
                removeBtn.innerHTML = '<i class="fas fa-times"></i>';
                
                removeBtn.addEventListener('click', e => {
                    e.preventDefault();
                    previewContainer.remove();
                    uploadContainer.style.display = 'block';
                    uploadContainer.querySelector('input[type="file"]').value = '';
                });

                previewContainer.appendChild(img);
                previewContainer.appendChild(removeBtn);
                uploadContainer.parentElement.appendChild(previewContainer);
            }
            previewContainer.querySelector('img').src = e.target.result;
            uploadContainer.style.display = 'none';
        };
        reader.readAsDataURL(file);
    }

    // 表单验证
    function validateForm(form) {
        const requiredFields = form.querySelectorAll('[required]');
        let isValid = true;

        requiredFields.forEach(field => {
            if (!field.value) {
                isValid = false;
                field.classList.add('error');
                
                // 创建或更新错误提示
                let errorMsg = field.parentElement.querySelector('.error-message');
                if (!errorMsg) {
                    errorMsg = document.createElement('span');
                    errorMsg.className = 'error-message';
                    field.parentElement.appendChild(errorMsg);
                }
                errorMsg.textContent = '创建错误';
            } else {
                field.classList.remove('error');
                const errorMsg = field.parentElement.querySelector('.error-message');
                if (errorMsg) errorMsg.remove();
            }
        });

        // 价格验证
        const price = form.querySelector('#price');
        if (price.value && parseFloat(price.value) <= 0) {
            isValid = false;
            price.classList.add('error');
            let errorMsg = price.parentElement.querySelector('.error-message');
            if (!errorMsg) {
                errorMsg = document.createElement('span');
                errorMsg.className = 'error-message';
                price.parentElement.appendChild(errorMsg);
            }
            errorMsg.textContent = '价格必须大于0';
        }

        // 库存验证
        const stock = form.querySelector('#stock');
        if (stock.value && parseInt(stock.value) < 0) {
            isValid = false;
            stock.classList.add('error');
            let errorMsg = stock.parentElement.querySelector('.error-message');
            if (!errorMsg) {
                errorMsg = document.createElement('span');
                errorMsg.className = 'error-message';
                stock.parentElement.appendChild(errorMsg);
            }
            errorMsg.textContent = '库存不能为负数';
        }

        return isValid;
    }

    // 删除商品
    function deleteProduct(id) {
        if (confirm('确定要删除这个商品吗？')) {
            products = products.filter(p => p.id !== id);
            updateProductTable(products);
            updateStatistics();
        }
    }

    // 查看商品详情
    function viewProduct(id) {
        const product = products.find(p => p.id === id);
        if (!product) return;

        // 创建查看详情的模态框
        const viewModal = document.createElement('div');
        viewModal.className = 'modal view-modal';
        viewModal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3>查看商品详情</h3>
                    <button class="close-btn">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="product-view">
                        <div class="product-image">
                            <img src="${product.image}" alt="${product.name}">
                        </div>
                        <div class="product-details">
                            <div class="detail-item">
                                <label>商品名称：</label>
                                <span>${product.name}</span>
                            </div>
                            <div class="detail-item">
                                <label>作者：</label>
                                <span>${product.author}</span>
                            </div>
                            <div class="detail-item">
                                <label>商品编码：</label>
                                <span>${product.code}</span>
                            </div>
                            <div class="detail-item">
                                <label>分类：</label>
                                <span>${product.category}</span>
                            </div>
                            <div class="detail-item">
                                <label>价格：</label>
                                <span>¥${product.price.toFixed(2)}</span>
                            </div>
                            <div class="detail-item">
                                <label>库存：</label>
                                <span>${product.stock}</span>
                            </div>
                            <div class="detail-item">
                                <label>销量：</label>
                                <span>${product.sales}</span>
                            </div>
                            <div class="detail-item">
                                <label>状态：</label>
                                <span class="status-tag ${product.status === '上架中' ? 'status-active' : 'status-inactive'}">
                                    ${product.status}
                                </span>
                            </div>
                            <div class="detail-item">
                                <label>商品描述：</label>
                                <p>${product.description}</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary close-view">关闭</button>
                </div>
            </div>
        `;

        document.body.appendChild(viewModal);
        document.body.style.overflow = 'hidden';

        // 关闭查看详情模态框
        const closeViewModal = () => {
            viewModal.remove();
            document.body.style.overflow = '';
        };

        viewModal.querySelector('.close-btn').addEventListener('click', closeViewModal);
        viewModal.querySelector('.close-view').addEventListener('click', closeViewModal);
        viewModal.addEventListener('click', e => {
            if (e.target === viewModal) closeViewModal();
        });
    }

    // 编辑商品
    function editProduct(id) {
        const product = products.find(p => p.id === id);
        if (!product) return;

        // 打开编辑模态框
        modal.style.display = 'block';
        document.body.style.overflow = 'hidden';

        // 填充表单数据
        const editForm = document.getElementById('addProductForm');
        editForm.querySelector('[name="productName"]').value = product.name;
        editForm.querySelector('[name="author"]').value = product.author;
        editForm.querySelector('[name="productCode"]').value = product.code;
        editForm.querySelector('[name="category"]').value = product.category;
        editForm.querySelector('[name="price"]').value = product.price;
        editForm.querySelector('[name="stock"]').value = product.stock;
        editForm.querySelector('[name="status"]').value = product.status === '上架中' ? '1' : '2';
        editForm.querySelector('[name="description"]').value = product.description;

        // 显示当前商品图片
        const imageUpload = editForm.querySelector('.image-upload');
        let imagePreview = editForm.querySelector('.image-preview');
        if (!imagePreview) {
            imagePreview = document.createElement('div');
            imagePreview.className = 'image-preview';
            const img = document.createElement('img');
            img.src = product.image;
            const removeBtn = document.createElement('button');
            removeBtn.className = 'remove-image';
            removeBtn.innerHTML = '<i class="fas fa-times"></i>';
            
            removeBtn.addEventListener('click', e => {
                e.preventDefault();
                imagePreview.remove();
                fileInput.value = '';
                imageUpload.style.display = 'block';
            });

            imagePreview.appendChild(img);
            imagePreview.appendChild(removeBtn);
            imageUpload.parentNode.insertBefore(imagePreview, imageUpload.nextSibling);
        }
        imageUpload.style.display = 'none';

        // 修改表单提交事件
        const originalSubmitHandler = editForm.onsubmit;
        editForm.onsubmit = function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            
            // 更新商品数据
            const updatedProduct = {
                ...product,
                name: formData.get('productName'),
                author: formData.get('author'),
                code: formData.get('productCode'),
                category: formData.get('category'),
                price: parseFloat(formData.get('price')),
                stock: parseInt(formData.get('stock')),
                status: formData.get('status') === '1' ? '上架中' : '已下架',
                description: formData.get('description')
            };

            // 如果上传了新图片
            const newImage = formData.get('image');
            if (newImage.size > 0) {
                updatedProduct.image = URL.createObjectURL(newImage);
            }

            // 更新商品列表
            const index = products.findIndex(p => p.id === id);
            products[index] = updatedProduct;

            // 更新表格和统计
            updateProductTable(products);
            updateStatistics();
            closeModal();
            alert('商品更新成功！');

            // 恢复原始提交处理程序
            editForm.onsubmit = originalSubmitHandler;
        };
    }

    // 为查看和编辑按钮添加事件监听
    function addActionButtonListeners(row, product) {
        const viewBtn = row.querySelector('.view');
        const editBtn = row.querySelector('.edit');
        
        viewBtn.addEventListener('click', () => viewProduct(product.id));
        editBtn.addEventListener('click', () => editProduct(product.id));
    }

    // 添加商品按钮点击事件
    if (addProductBtn) {
        addProductBtn.addEventListener('click', () => {
            openModal();
        });
    } else {
        console.error('未找到添加商品按钮，请检查HTML结构');
    }
    const addProductButton = document.querySelector('.action-group .btn.btn-primary');
    const addProductModal = document.getElementById('addProductModal');
    const closeButton = document.querySelector('.close-btn');
    const cancelButton = document.getElementById('cancelBtn');

// 点击添加商品按钮时显示模态框
    addProductButton.addEventListener('click', function() {
        addProductModal.style.display = 'block';
    });

// 点击关闭按钮或取消按钮时隐藏模态框
    closeButton.addEventListener('click', function() {
        addProductModal.style.display = 'none';
    });

    cancelButton.addEventListener('click', function() {
        addProductModal.style.display = 'none';
    });

// 点击模态框外部区域时隐藏模态框
    window.addEventListener('click', function(event) {
        if (event.target === addProductModal) {
            addProductModal.style.display = 'none';
        }
    });
    // 初始化页面
    initializePage();
}); 